﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2018/11/15 19:39:47
*说明：<Function>
/**********************************************************************/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebSocketSharp;
using Model;
using Model.Data;

namespace WebApi.Helper
{
    public class WssMsgHelper
    {
        private static DateTime startTime { get; set; }
        /// <summary>
        /// 发送打印请求
        /// </summary>
        /// <param name="ToUser"></param>
        /// <returns></returns>
        public static RespData SendPrint(dynamic data)
        {
            startTime = DateTime.Now;
            RespData result = RespData.GetRes();

            string tag = data.tag;
            //ItemType.Type type = ItemType.Match(tag);

            ClientMsg msd = new ClientMsg
            {
                action = 3,
                actionName = "打印",
                msg = "",
                msgContent = JsonConvert.SerializeObject(data),
                seqId = DateTime.Now.Ticks,
                from = tag
            };
            var str = JsonConvert.SerializeObject(msd); 
            var ws = new WebSocket(Gvar.WssServer);
            ws.Connect();
            bool exit = false;
            ClientMsg res = new ClientMsg();
            res.seqId = -1;
            ws.OnMessage += (sender, e) =>
            {
                res = JsonConvert.DeserializeObject<ClientMsg>(e.Data);
                if (res.seqId>0) exit = true;
            };
            ws.OnOpen += (sender, e) =>
            {
                Console.Write("ok");
            };
            ws.OnError += (sender, e) =>
            {
                result = RespData.GetError(msg: e.Message);
                LogHelper.Error(e.Message);
            };
            try
            {
                ws.Send(str);
                while (!exit)
                {
                    TimeSpan ts = DateTime.Now.Subtract(startTime);
                    if (ts.TotalSeconds >= 20) break;

                }
                ws.Close();
                if (res.seqId != 0) LogHelper.Error($"发送打印信息出错 Url:{Gvar.WssServer}");
                if (res.seqId == -1) result = RespData.GetError(msg: "发送打印信息失败");
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                result = RespData.GetError(msg: ex.Message);
                return result;
            }

            return result;

        }
    }   
}